package com.woniu.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.util.HashMap;
import java.util.Map;

/**
 * 生成jwt工具类
 * 1.创建jwt
 * 2.校验jwt是否合法
 * 3.返回载荷部分
 */
public class JWTUtil {

    private static final String KEY="hehehehehehehehehehehehehehehehehehehehe";

    public static String creatJWT(String username) throws JOSEException {
        //创建JWT头部
        JWSHeader jwsHeader=new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT)
                .build();
        //创建载荷
        Map map=new HashMap();
        map.put("username",username);
        Payload payload=new Payload(map);

        JWSObject jwsObject = new JWSObject(jwsHeader, payload);

        JWSSigner jwsSigner=new MACSigner(KEY);
        jwsObject.sign(jwsSigner);

        return jwsObject.serialize();
    }

    /**
     * 解密 jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public static boolean decode(String jwt) throws Exception {
        JWSVerifier jwsVerifier=new MACVerifier(KEY);
        JWSObject parse = JWSObject.parse(jwt);
        return parse.verify(jwsVerifier);
    }

    /**
     * 获取载荷内容
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Map getPayload(String jwt) throws Exception {
        JWSObject jwsObject = JWSObject.parse(jwt);
        return jwsObject.getPayload().toJSONObject();
    }

}
